import type { HTMLAttributes, SetupContext } from "vue";
import { defineComponent, onMounted, ref } from "vue";
import Button from "./Button";

type CountDownEmits = {
  done: () => void;
};

/**
 * 这里如果不标注到 props 上，在使用时，就没有代码提示
 */
type CountDownEmitsProps = {
  onDone?: () => void;
};

/**
 * 自定义属性
 */
type CountDownCustomProps = {
  start: number;
};

/**
 * CountDown 的属性由接受透传 props 的组件的属性、自定义属性、事件回调类型标注这三部分构成。
 */
type CountDownProps = HTMLAttributes & CountDownCustomProps & CountDownEmitsProps;

const CountDown = defineComponent<CountDownProps, CountDownEmits>({
  /**
   * 这里不声明 start 为 property，就会被透传到最外面的 div 上
   */
  props: ["start"],
  setup({ start }: CountDownProps, { emit }: SetupContext<CountDownEmits>) {
    const current = ref(0);

    const countDown = () => {
      current.value = start;
      const i = setInterval(() => {
        current.value = Math.max(current.value - 1, 0);
        if (current.value <= 0) {
          clearInterval(i);
          emit("done");
        }
      }, 1000);
    };

    onMounted(countDown);

    return () => (
      <div>
        {current.value}
        {current.value <= 0 ? <Button onClick={countDown}>Reset</Button> : null}
      </div>
    );
  },
});

export default CountDown;
